<template>
  <div>
    <a-card class="card" title="编辑盘库单">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-form-item v-show="false"><a-input v-decorator="['code']" /></a-form-item>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item label="盘库类型">
              <a-select style="width: 100%" placeholder="请选择盘库类型" v-decorator="['type', {rules: [{ required: true, message: '请选择盘库类型' }]}]">
                <a-select-option v-for="(item,index) in inventoryTypeData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              label="盘库范围">
              <a-tree
                v-model="checkedKeys"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                :replaceFields="replaceFields"
                @expand="onExpand"
                @select="onSelect"
                @check="onCheck"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col>
            <a-form-item
              label="备注">
              <a-textarea placeholder="请输入备注" v-decorator="['remark']"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <a-button class="subButton" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
  import FooterToolBar from '@/components/FooterToolbar'
  import { inventoryEdit, inventoryDetail } from '@/api/modular/main/stock/inventory/inventoryManage'
  import { storehouseTree } from '@/api/modular/main/base/storehouse/storehouseManage'
  export default {
    components: {
      FooterToolBar
    },
    data () {
      return {
        code: '',
        loading: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        inventoryTypeData: [],
        expandedKeys: ['0'],
        autoExpandParent: true,
        checkedKeys: [],
        locationCodeList: [],
        selectedKeys: [],
        treeData: [],
        replaceFields: {
          children: 'children',
          title: 'label',
          key: 'code'
        },
        selectStorehourseNodes: []
      }
    },
    created () {
      const inventoryTypeOption = this.$options
      this.inventoryTypeData = inventoryTypeOption.filters['dictData']('inventory_type')
      this.selectStorehourseTree()
    },
    activated () {
      const oldCode = this.code
      this.code = this.$route.query.code
      console.log()
      if (oldCode !== this.code) {
        inventoryDetail(this.code).then((res) => {
          if (res.success) {
            this.edit(res.data)
          } else {
            this.$message.error('数据加载失败:' + res.message)
          }
        })
      }
    },
    methods: {
      // 初始化方法
      edit (record) {
        console.log(record)
        this.form.setFieldsValue(
          {
            id: this.$praseStrEmpty(record.id),
            code: this.$praseStrEmpty(record.code),
            type: this.$praseStrEmpty(record.type),
            remark: this.$praseStrEmpty(record.remark)
          }
        )
        this.checkedKeys = record.locationCodeList
        this.locationCodeList = record.locationCodeList
      },
      selectStorehourseTree() {
        storehouseTree({}).then((res) => {
          this.treeData = res.data
        })
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      onCheck(checkedKeys, event) {
        this.checkedKeys = checkedKeys
        this.selectStorehourseNodes = []
        this.locationCodeList = []
        if (event.checkedNodes && event.checkedNodes.length > 0) {
          event.checkedNodes.forEach(item => {
            if (item.data.props.type === 'LOCATION') {
              this.locationCodeList.push(item.data.props.code)
            }
            this.selectStorehourseNodes.push({
              code: item.data.props.code,
              type: item.data.props.type,
              name: item.data.props.label
            })
          })
        }
        console.log(this.locationCodeList)
      },
      onSelect(selectedKeys) {
        this.selectedKeys = selectedKeys
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
            if (this.locationCodeList.length > 0) {
              values['locationCodeList'] = this.locationCodeList
            } else {
              this.$message.error('请先选择需要盘库的库位')
              this.confirmLoading = false
              return
            }
            inventoryEdit(values).then((res) => {
              if (res.success) {
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error('编辑失败:' + res.message)
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.code = ''
        this.form.resetFields()
        this.visible = false
        this.checkedKeys = []
        this.locationCodeList = []
        this.selectedKeys = []
        this.$multiTab.closeAndOpen('/inventory')
      }
    }
  }
</script>
